package com.manager.commons.basemanage.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.manager.BaseDao;
import com.manager.commons.basemanage.struts.form.BaseDataForm;
import com.manager.commons.page.PageBean;

public class BaseManageDao extends BaseDao{
	
	
	
	
	
	
	/**
	 * 数据字典查询
	 * @param nameType
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List selectBaseDataList(String nameType){
		
		StringBuffer buf = new StringBuffer();
		
		buf.append("from BaseData ");  
		
		if(nameType != null && !nameType.equals("")){
			buf.append("where typeName like ");
			buf.append("'%"+nameType+"%'");
		} 
		
		return  this.getHibernateTemplate().find(buf.toString()); 
	}
	
	public Integer getAllCountBaseData(BaseDataForm baseDataForm){
		//储存查询条件的buffer		
		StringBuffer buf = new StringBuffer(); 
		
		buf.append("select count(*) from BaseData  where  1=1");
		
		//查询字符串		
		String strSql = getStringBuffer(baseDataForm,buf).toString();
		
		return Integer.parseInt(this.getHibernateTemplate().find(strSql).get(0).toString());
	}
	
	public List searchBaseData(BaseDataForm baseDataForm,final PageBean pageBean){  
		StringBuffer buf = new StringBuffer();
	    
		//返回list集合
	    List list = null; 
		
		buf.append("from BaseData  where 1=1 "); 

		//查询字符串条件		
		buf = getStringBuffer(baseDataForm,buf); 
		
		//传递查询条件buf值		
		pageBean.setStringBuffer(buf);
		
		//分页取得字符串集合
		list = getHibernateTemplate().executeFind(new HibernateCallback() {
			
			public Object doInHibernate(Session session)			
					throws HibernateException, SQLException {
				
				Query query = session.createQuery(pageBean.getStringBuffer().toString()+" order by id Desc ");	
				
				//设置开始页
 				query.setFirstResult(pageBean.getPageSize()*(pageBean.getPageIndex()-1));
 				
 				//设置结束页
 				query.setMaxResults(pageBean.getPageSize());
 				
				List list = query.list();
				
				return list;
			}
		}
		); 
		return list;
	}
	/**
	 * 查询条件的拼接
	 * @param selectField
	 * @param selectValue
	 * @param buf
	 * @return 拼接后的StringBuffer
	 */
	private StringBuffer getStringBuffer(BaseDataForm baseDataForm,StringBuffer buf){ 

		if(StringUtils.isNotBlank(baseDataForm.getTypeName())){
			buf.append(" and  typeName like ");
			buf.append("'%"+baseDataForm.getTypeName()+"%'");
		} 
		return buf;
 
	}
}
